import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  Mic, MicOff, Video, VideoOff, Pause, Play, Square,
  Users, FileText, Settings, Volume2, VolumeX, Maximize2,
  Clock, Calendar, MapPin, Tag, Save, X, Star
} from 'lucide-react'
import './MeetingRecord.css'

const MeetingRecord = () => {
  const navigate = useNavigate()
  const { id } = useParams()
  
  const [isRecording, setIsRecording] = useState(false)
  const [isPaused, setIsPaused] = useState(false)
  const [audioEnabled, setAudioEnabled] = useState(true)
  const [videoEnabled, setVideoEnabled] = useState(false)
  const [volumeEnabled, setVolumeEnabled] = useState(true)
  const [duration, setDuration] = useState(0)
  const [showTranscript, setShowTranscript] = useState(true)
  const [showSettings, setShowSettings] = useState(false)
  const [highlights, setHighlights] = useState([]) // 重点标记列表

  // Mock meeting data
  const meetingData = {
    title: '产品设计评审会议',
    date: '2024-01-20',
    time: '14:00 - 16:00',
    location: '会议室A / 线上',
    participants: ['张三', '李四', '王五', '赵六'],
    tags: ['产品设计', '评审', '季度规划']
  }

  // Mock transcript data
  const [transcript, setTranscript] = useState([
    { id: 1, speaker: '张三', time: '00:00:15', text: '大家好,今天我们主要讨论新产品的设计方案。', isHighlight: false },
    { id: 2, speaker: '李四', time: '00:00:32', text: '我已经准备好了初步的设计稿,待会儿给大家展示。', isHighlight: false },
    { id: 3, speaker: '王五', time: '00:00:48', text: '好的,我们先看一下整体的产品定位和目标用户群体。', isHighlight: false },
    { id: 4, speaker: '张三', time: '00:01:05', text: '根据市场调研,我们的目标用户主要是25-40岁的职场人士。', isHighlight: false },
  ])

  // Timer effect
  useEffect(() => {
    let interval
    if (isRecording && !isPaused) {
      interval = setInterval(() => {
        setDuration(prev => prev + 1)
      }, 1000)
    }
    return () => clearInterval(interval)
  }, [isRecording, isPaused])

  const formatDuration = (seconds) => {
    const hrs = Math.floor(seconds / 3600)
    const mins = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  const handleStartRecording = () => {
    setIsRecording(true)
    setIsPaused(false)
  }

  const handlePauseRecording = () => {
    setIsPaused(!isPaused)
  }

  const handleStopRecording = () => {
    if (window.confirm('确定要结束会议录制吗?')) {
      setIsRecording(false)
      setIsPaused(false)
      // Save and navigate
      navigate('/resource-library')
    }
  }

  const handleSaveDraft = () => {
    alert('会议已保存为草稿')
  }

  // 一键划重点功能
  const handleHighlight = () => {
    if (!isRecording) {
      alert('请先开始录制')
      return
    }

    const currentTime = formatDuration(duration)

    // 获取当前时间点前后的上下文（前后各2条记录）
    const contextRange = 2
    const recentTranscripts = transcript.slice(-contextRange * 2)

    // 标记最近的转写记录为重点
    const updatedTranscript = transcript.map((item, index) => {
      if (index >= transcript.length - contextRange) {
        return { ...item, isHighlight: true }
      }
      return item
    })

    setTranscript(updatedTranscript)

    // 保存重点信息
    const highlightData = {
      id: highlights.length + 1,
      timestamp: currentTime,
      duration: duration,
      context: recentTranscripts,
      markedAt: new Date().toISOString()
    }

    setHighlights([...highlights, highlightData])

    // 视觉反馈
    const notification = document.createElement('div')
    notification.className = 'highlight-notification'
    notification.innerHTML = `
      <div class="notification-content">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
        </svg>
        <span>已标记重点 (${currentTime})</span>
      </div>
    `
    document.body.appendChild(notification)

    setTimeout(() => {
      notification.classList.add('show')
    }, 10)

    setTimeout(() => {
      notification.classList.remove('show')
      setTimeout(() => {
        document.body.removeChild(notification)
      }, 300)
    }, 2000)

    console.log('重点已标记:', highlightData)
  }

  return (
    <div className="meeting-record">
      {/* Header */}
      <div className="meeting-header">
        <div className="meeting-info">
          <h1>{meetingData.title}</h1>
          <div className="meeting-meta">
            <span className="meta-item">
              <Calendar size={16} />
              {meetingData.date}
            </span>
            <span className="meta-item">
              <Clock size={16} />
              {meetingData.time}
            </span>
            <span className="meta-item">
              <MapPin size={16} />
              {meetingData.location}
            </span>
          </div>
        </div>
        
        <div className="meeting-actions">
          <button className="icon-btn" onClick={handleSaveDraft}>
            <Save size={20} />
          </button>
          <button className="icon-btn" onClick={() => setShowSettings(!showSettings)}>
            <Settings size={20} />
          </button>
          <button className="icon-btn close-btn" onClick={() => navigate(-1)}>
            <X size={20} />
          </button>
        </div>
      </div>

      {/* Main Content */}
      <div className="meeting-content">
        {/* Left Panel - Video/Audio Display */}
        <div className="media-panel">
          <div className="video-container">
            {videoEnabled ? (
              <div className="video-placeholder">
                <Video size={64} />
                <p>视频画面</p>
              </div>
            ) : (
              <div className="audio-visualizer">
                <div className="visualizer-bars">
                  {[...Array(20)].map((_, i) => (
                    <div 
                      key={i} 
                      className="bar" 
                      style={{ 
                        animationDelay: `${i * 0.1}s`,
                        animationPlayState: isRecording && !isPaused ? 'running' : 'paused'
                      }}
                    />
                  ))}
                </div>
                <Mic size={48} className="mic-icon" />
                <p>音频录制中</p>
              </div>
            )}
          </div>

          {/* Recording Status */}
          <div className="recording-status">
            <div className="status-indicator">
              {isRecording && (
                <>
                  <span className={`rec-dot ${isPaused ? 'paused' : ''}`}></span>
                  <span className="status-text">
                    {isPaused ? '已暂停' : '录制中'}
                  </span>
                </>
              )}
              {!isRecording && (
                <span className="status-text ready">准备就绪</span>
              )}
            </div>
            <div className="duration">{formatDuration(duration)}</div>
          </div>

          {/* Control Buttons */}
          <div className="control-panel">
            <div className="control-group">
              <button 
                className={`control-btn ${!audioEnabled ? 'disabled' : ''}`}
                onClick={() => setAudioEnabled(!audioEnabled)}
                title={audioEnabled ? '关闭麦克风' : '开启麦克风'}
              >
                {audioEnabled ? <Mic size={24} /> : <MicOff size={24} />}
              </button>
              
              <button 
                className={`control-btn ${!videoEnabled ? 'disabled' : ''}`}
                onClick={() => setVideoEnabled(!videoEnabled)}
                title={videoEnabled ? '关闭摄像头' : '开启摄像头'}
              >
                {videoEnabled ? <Video size={24} /> : <VideoOff size={24} />}
              </button>
              
              <button 
                className={`control-btn ${!volumeEnabled ? 'disabled' : ''}`}
                onClick={() => setVolumeEnabled(!volumeEnabled)}
                title={volumeEnabled ? '静音' : '取消静音'}
              >
                {volumeEnabled ? <Volume2 size={24} /> : <VolumeX size={24} />}
              </button>

              <button
                className="control-btn"
                title="全屏"
              >
                <Maximize2 size={24} />
              </button>

              <button
                className={`control-btn highlight-btn ${isRecording ? 'active' : ''}`}
                onClick={handleHighlight}
                title="一键划重点"
                disabled={!isRecording}
              >
                <Star size={24} />
              </button>
            </div>

            <div className="main-controls">
              {!isRecording ? (
                <button className="main-btn start-btn" onClick={handleStartRecording}>
                  <Play size={28} />
                  开始录制
                </button>
              ) : (
                <>
                  <button className="main-btn pause-btn" onClick={handlePauseRecording}>
                    {isPaused ? <Play size={28} /> : <Pause size={28} />}
                    {isPaused ? '继续' : '暂停'}
                  </button>
                  <button className="main-btn stop-btn" onClick={handleStopRecording}>
                    <Square size={28} />
                    结束
                  </button>
                </>
              )}
            </div>
          </div>
        </div>

        {/* Right Panel - Transcript & Info */}
        <div className="info-panel">
          {/* Tabs */}
          <div className="panel-tabs">
            <button 
              className={`tab ${showTranscript ? 'active' : ''}`}
              onClick={() => setShowTranscript(true)}
            >
              <FileText size={20} />
              实时转写
            </button>
            <button 
              className={`tab ${!showTranscript ? 'active' : ''}`}
              onClick={() => setShowTranscript(false)}
            >
              <Users size={20} />
              会议信息
            </button>
          </div>

          {/* Content */}
          {showTranscript ? (
            <div className="transcript-container">
              <div className="transcript-header">
                <h3>会议记录</h3>
                <div className="transcript-stats">
                  <span className="transcript-count">{transcript.length} 条</span>
                  {highlights.length > 0 && (
                    <span className="highlight-count">
                      <Star size={14} />
                      {highlights.length} 个重点
                    </span>
                  )}
                </div>
              </div>
              <div className="transcript-list">
                {transcript.map(item => (
                  <div key={item.id} className={`transcript-item ${item.isHighlight ? 'highlighted' : ''}`}>
                    <div className="transcript-meta">
                      <span className="speaker">{item.speaker}</span>
                      <span className="timestamp">{item.time}</span>
                      {item.isHighlight && (
                        <span className="highlight-badge">
                          <Star size={12} />
                          重点
                        </span>
                      )}
                    </div>
                    <p className="transcript-text">{item.text}</p>
                  </div>
                ))}
              </div>
              {isRecording && (
                <div className="transcript-typing">
                  <span className="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </span>
                  <span>正在转写...</span>
                </div>
              )}
            </div>
          ) : (
            <div className="meeting-details">
              <div className="detail-section">
                <h3>参会人员</h3>
                <div className="participants-list">
                  {meetingData.participants.map((participant, index) => (
                    <div key={index} className="participant-item">
                      <div className="participant-avatar">
                        {participant.charAt(0)}
                      </div>
                      <span>{participant}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="detail-section">
                <h3>会议标签</h3>
                <div className="tags-list">
                  {meetingData.tags.map((tag, index) => (
                    <div key={index} className="tag-item">
                      <Tag size={16} />
                      {tag}
                    </div>
                  ))}
                </div>
              </div>

              <div className="detail-section">
                <h3>录制设置</h3>
                <div className="settings-list">
                  <div className="setting-row">
                    <span>音频质量</span>
                    <span className="setting-value">高品质</span>
                  </div>
                  <div className="setting-row">
                    <span>视频分辨率</span>
                    <span className="setting-value">1920x1080</span>
                  </div>
                  <div className="setting-row">
                    <span>自动转写</span>
                    <span className="setting-value">已启用</span>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default MeetingRecord

